﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;

namespace WpfDemo.Common
{
    /// <summary>
    /// DES加密、解密帮助类
    /// </summary>
    public class DESEncrypt
    {
        private static readonly byte[] Key = Encoding.UTF8.GetBytes("1234567812345678"); // 16字节密钥
        private static readonly byte[] IV = Encoding.UTF8.GetBytes("1234567812345678");  // 16字节初始化向量

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="plainText"></param>
        /// <returns></returns>
        public static string Encrypt(string plainText)
        {
            using var aes = Aes.Create();
            aes.Key = Key;
            aes.IV = IV;

            var encryptor = aes.CreateEncryptor(aes.Key, aes.IV);

            using var ms = new MemoryStream();
            using (var cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
            {
                using (var sw = new StreamWriter(cs))
                {
                    sw.Write(plainText);
                }
            }

            return Convert.ToBase64String(ms.ToArray());
        }
        /// <summary>
        /// 解密数据
        /// </summary>
        /// <param name="cipherText"></param>
        /// <returns></returns>
        public static string Decrypt(string cipherText)
        {
            using var aes = Aes.Create();
            aes.Key = Key;
            aes.IV = IV;

            var decryptor = aes.CreateDecryptor(aes.Key, aes.IV);

            byte[] bytes = Convert.FromBase64String(cipherText);

            using var ms = new MemoryStream(bytes);
            using (var cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
            {
                using var sr = new StreamReader(cs);
                return sr.ReadToEnd();
            }
        }
    }
}
